package com.nineclock.approve.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nineclock.approve.dto.ApproveGroupDefinitionDto;
import com.nineclock.approve.mapper.ApproveDefinitionMapper;
import com.nineclock.approve.pojo.ApproveDefinition;
import com.nineclock.approve.service.ApproveDefinitionService;
import com.nineclock.common.threadlocal.CurrentUserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author 黑马程序员
 * @Company http://www.ithiema.com
 * @Version 1.0
 */
@Service
@Slf4j
public class ApproveDefinitionServiceImpl implements ApproveDefinitionService {


    @Autowired
    ApproveDefinitionMapper approveDefinitionMapper;

    @Override
    public List<ApproveGroupDefinitionDto> queryApproveGroupDefinition() {

        List<ApproveGroupDefinitionDto> list = new ArrayList<>();

        //查询所有的审批流程对象
        LambdaQueryWrapper<ApproveDefinition> approveDefinitionQw = new LambdaQueryWrapper<>();
        approveDefinitionQw.eq(ApproveDefinition::getCompanyId, CurrentUserHolder.get().getCompanyId());
        approveDefinitionQw.eq(ApproveDefinition::getIsValid, "1");
        //获取 该企业的所有的有效审批流程对象
        List<ApproveDefinition> approveDefinitionList = approveDefinitionMapper.selectList(approveDefinitionQw);
        if(CollectionUtil.isNotEmpty(approveDefinitionList)){
            //按照group_type进行分类
            Map<String, List<ApproveDefinition>> map = approveDefinitionList.stream().collect(Collectors.groupingBy(ApproveDefinition::getGroupType));
            //map集合中的 key 的集合
            Set<String> keySets = map.keySet();

            for (String key : keySets) {
                //一个key对应  一个 ApproveGroupDefinitionDto
                ApproveGroupDefinitionDto definitionDto = new ApproveGroupDefinitionDto();
                //key对应 groupType  类型属性
                definitionDto.setGroupType(key);
                //value 对应 审批流程列表
                definitionDto.setDefinitionList(map.get(key));
                list.add(definitionDto);
            }
        }


        return list;
    }
}
